﻿using System;
using System.ComponentModel;
using System.Collections.Generic;
using System.Diagnostics;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Collections.ObjectModel;
using System.Net;
using FloodFree.Phone.ViewModels;
using Newtonsoft.Json.Linq;


namespace FloodFree.Phone
{
    public class MainViewModel : BaseViewModel
    {
        public MainViewModel()
        {
            this.Items = new ObservableCollection<ItemViewModel>();
        }

        public ObservableCollection<ItemViewModel> Items { get; private set; }


        public bool IsDataLoaded
        {
            get;
            private set;
        }

        public void LoadData()
        {


            string WS_URL = "http://floodfree.cloudapp.net/api/cities";

            Uri uri = new Uri(WS_URL, UriKind.Absolute);
            WebClient client = new WebClient();
            client.DownloadStringCompleted += (source, args) =>
            {
                if (args.Error != null)
                {
                    MessageBox.Show("Erro ao buscar os dados.");
                    return;
                }

                List<ItemViewModel> cities = CitiesFromJson(args.Result);
                foreach (ItemViewModel item in cities)
                {
                    this.Items.Add(item);
                }
                this.IsDataLoaded = true;
                
            };
            client.DownloadStringAsync(uri);

            
            
        }

        private List<ItemViewModel> CitiesFromJson(String json)
        {
            List<ItemViewModel> cities = new List<ItemViewModel>();
            JObject o = JObject.Parse(json);
            JArray citiesJson = (JArray)o["Cities"];
            foreach (JObject cityJson in citiesJson)
            {
                ItemViewModel city = new ItemViewModel {Id = (int)cityJson["Id"],
                                                        LineOne = (string)cityJson["Name"] };
                cities.Add(city);
            }
           

            return cities;
        }
    }
}